import type { MultipleConditionSearchSchema } from '@/components/multiple-condition-search'
import { getApplicationsApi } from '@/apis/modules/application.ts'

export default function useConfig() {
  const { allRegionOptions } = useRegions()

  const applications = ref<LabelValue[]>([])

  async function getApplications() {
    const res = await getApplicationsApi({ limit: 500 })
    applications.value = res.list!.map((item) => {
      return { label: item.name!, value: item.app_id! }
    })
  }
  onMounted(getApplications)

  const searchSchema = computed<MultipleConditionSearchSchema>(() => {
    return {
      placeholder: '默认按照实例ID搜索',
      widgets: [
        {
          type: 'input',
          field: 'instance_name_id',
          label: '实例ID',
          placeholder: '请输入实例ID',
        },
        {
          type: 'select',
          field: 'app_id',
          label: '所属应用',
          placeholder: '请选择所属应用',
          options: applications.value,
        },
      ],
    }
  })

  const tableColumns = buildColumns([
    {
      title: '实例ID',
      dataIndex: 'instance_name_id',
    },
    {
      title: '所属应用',
      dataIndex: 'app_id',
      render({ record }) {
        return getOptionLabel(record.app_id, applications.value)
      },
    },
    {
      title: '区域',
      dataIndex: 'region_id',
      render({ record }) {
        return getOptionLabel(record.region_id, allRegionOptions)
      },
    },
    {
      title: 'CPU 使用率',
      dataIndex: 'cpu_usage_rate',
      sortable: sortableSettings,
      render({ record }) {
        return `${record.cpu_usage_rate}%`
      },
    },
    {
      title: '内存使用量',
      dataIndex: 'memory_usage_amount',
      sortable: sortableSettings,
      render({ record }) {
        return formatBytes(
          Number(record.memory_usage_amount) * 1024 ** 2,
        ).toString()
      },
    },
    {
      title: '公网传入流量',
      dataIndex: 'network_incoming_bytes',
      sortable: sortableSettings,
      render({ record }) {
        return formatBytes(record.network_incoming_bytes).toString()
      },
    },
    {
      title: '公网传出流量',
      dataIndex: 'network_outgoing_bytes',
      sortable: sortableSettings,
      render({ record }) {
        return formatBytes(record.network_outgoing_bytes).toString()
      },
    },
  ])

  return {
    allRegionOptions,
    applications,
    searchSchema,
    tableColumns,
  }
}
